﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

using ALE_Server.Plugin;

namespace ALE_Server.Plugin.Notifiers
{
    public class FTPNotifier  : Notifier
    {
        private string m_Server;
        private string m_UserName = "anonymous";
        private string m_Password = "";
        private string m_Directory = string.Empty;
        private string m_File = string.Empty;


        public FTPNotifier(string uri)
            : base(uri)
        {
        }

        public override void Init(string uri)
        {
            m_Uri = new Uri(uri);

            m_Server = m_Uri.Host;
            string UserInfo = m_Uri.UserInfo;

            if ((UserInfo != null) && (UserInfo.Length > 0))
            {
                if (UserInfo.IndexOf(":") > 0)
                {
                    m_UserName = UserInfo.Substring(0, UserInfo.IndexOf(":"));
                    m_Password = UserInfo.Substring(UserInfo.IndexOf(":") + 1);
                }
                else
                {
                    m_UserName = UserInfo;
                }
            }

            string Path = m_Uri.AbsolutePath;

            if ((Path != null) && (Path.Length > 0))
            {
                m_Directory = Path.Substring(0, Path.LastIndexOf("/"));
                m_File = Path.Substring(Path.LastIndexOf("/") + 1);
            }
        }

        public override void NotifySubscriber(ALE_Server.EC.ECReports reports)
        {
            try
            {
                FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create(m_Uri);
                FtpRequest.Proxy = null;
                FtpRequest.Method = WebRequestMethods.Ftp.UploadFile;

                Stream FtpStream = FtpRequest.GetRequestStream();
                WriteToOutputStream(reports, FtpStream);
                FtpStream.Close();

                FtpWebResponse Response = (FtpWebResponse) FtpRequest.GetResponse();
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(ex.Message);
            }
        }

        public override string GetURIFromFields()
        {
            StringBuilder Result = new StringBuilder();

            Result.Append("FTP://");
            Result.Append(m_Server);
            Result.Append(":");
            Result.Append(m_Directory);
            Result.Append("/");
            Result.Append(m_File);

            return Result.ToString();
        }
    }
}
